package cn.zhoujing.resource.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * @author zhoujing
 * @createTime 2023/11/24 - 0:12
 */
@Configuration
//开启oauth2,resource server模式
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    @Resource
    private TokenStore tokenStore;

    @Value("${security.oauth2.resource.id}")
    private String resourceId;

    /**
     * 指定当前资源的id和token存储策略
     *
     * @param resources 需要配置的资源信息
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 1、非JWT需要远程校验token
//        // 远程token校验
//        RemoteTokenServices tokenServices = new RemoteTokenServices();
//        tokenServices.setCheckTokenEndpointUrl("http://localhost:5001/oauth/check_token");
//        // 配置组件的clientId和密码，这个也是在auth中配置好的，资源服务相对于授权服务也是一个客户端，所以也需要clientId
//        tokenServices.setClientId("client1");
//        tokenServices.setClientSecret("123456");
//        resources
//                .resourceId("resource1")
//                .tokenServices(tokenServices)
//                .stateless(true);

        // 2、配置JWT后本地校验token
        resources
                .resourceId(resourceId)
                .tokenStore(tokenStore)
                .stateless(true);
    }

    /**
     * 设置请求权限和Header处理
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                // 指定不同请求方式访问资源所需要的权限。（如：查询 = read，更新 = write，新增 = write，删除 = write ）
                .antMatchers("/**").access("#oauth2.hasScope('scope1')")
//                .antMatchers(HttpMethod.GET,"/**").access("#oauth2.hasScope('user')")
//                .antMatchers(HttpMethod.PUT,"/**").access("#oauth2.hasScope('admin')")
//                .antMatchers(HttpMethod.POST,"/**").access("#oauth2.hasScope('admin')")
//                .antMatchers(HttpMethod.DELETE,"/**").access("#oauth2.hasScope('admin')")
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }


}
